package com.llb666.shop.payment.api.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.llb666.common.core.utils.DateUtil;
import com.llb666.common.core.web.response.BaseResponse;
import com.llb666.shop.payment.domain.entity.PayResult;
import com.llb666.shop.payment.domain.service.PaymentOrderService;
import com.llb666.shop.payment.domain.service.WxOrderService;
import com.llb666.shop.payment.infrastructure.config.AliPayConfig;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 异步通知 TODO 使用消息队列进行消息异步发送
 *
 * @author llb666
 */
@Tag(name = "支付异步通知接口")
@RestController
@RequestMapping(value = "/payment/notice")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class NotifyController {

    final static Logger log = LoggerFactory.getLogger(NotifyController.class);

    private final RestTemplate restTemplate;
    private final AliPayConfig aliPayConfig;
    private final WxOrderService wxOrderService;
    private final PaymentOrderService paymentOrderService;

    /**
     * 支付成功后的微信支付异步通知.
     */
    @PostMapping(value = "/wxpay")
    @Operation(summary = "微信支付异步通知")
    public void wxpay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付成功后的微信支付异步通知");
        // 获取微信支付结果
        PayResult payResult = wxOrderService.getWxPayResult(request.getInputStream());
        boolean isPaid = payResult.getReturn_code().equals("SUCCESS");
        // 查询该笔订单在微信那边是否成功支付
        // 支付成功，商户处理后同步返回给微信参数
        PrintWriter writer = response.getWriter();
        if (isPaid) {
            String merchantOrderId = payResult.getOut_trade_no();            // 商户订单号
            String wxFlowId = payResult.getTransaction_id();
            Integer paidAmount = payResult.getTotal_fee();

            // 操作商户自己的业务，比如修改订单状态等.
            String merchantReturnUrl = paymentOrderService.updateOrderPaid(merchantOrderId, paidAmount);

            log.info("************* 支付成功(微信支付异步通知) - 时间: {} *************", DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
            log.info("* 商户订单号: {}", merchantOrderId);
            log.info("* 微信订单号: {}", wxFlowId);
            log.info("* 实际支付金额: {}", paidAmount);
            log.info("*****************************************************************************");

            // 通知商城服务端订单已支付.
            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("merchantOrderId", merchantOrderId);
            String httpStatus = restTemplate.postForObject(merchantReturnUrl, requestEntity, String.class);
            log.info("*** 通知电商后返回的状态码 httpStatus: {} ***", httpStatus);

            // 通知微信已经收到消息，不要再给我发消息了，否则微信会10连击调用本接口.
            String noticeStr = setXML("SUCCESS", "");
            writer.write(noticeStr);
            writer.flush();
        } else {
            log.info("================================= 支付失败 =================================");
            // 支付失败
            String noticeStr = setXML("FAIL", "");
            writer.write(noticeStr);
            writer.flush();
        }

    }

    /**
     * 微信支付文档要求，返回xml格式.
     *
     * @param return_code 响应码
     * @param return_msg  响应消息
     * @return xml字符串
     */
    public static String setXML(String return_code, String return_msg) {
        return "<xml>"
                + "<return_code><![CDATA[" + return_code + "]]></return_code>"
                + "<return_msg><![CDATA[" + return_msg + "]]></return_msg>"
                + "</xml>";
    }

    /**
     * 支付成功后的支付宝异步通知.
     */
    @PostMapping(value = "/alipay")
    @Operation(summary = "支付宝支付异步通知")
    public String alipay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付成功后的支付宝异步通知");

        // 获取支付宝POST过来反馈信息.
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用.
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getCharset(),
                aliPayConfig.getSignType());
        // 如果验证成功 ---->
        if (signVerified) {
            // 商户订单号.
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
            // 支付宝交易号.
            String trade_no = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
            // 交易状态.
            String trade_status = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
            // 付款金额.
            String total_amount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1),
                    StandardCharsets.UTF_8);
            if (trade_status.equals("TRADE_SUCCESS")) {
                String merchantReturnUrl = paymentOrderService.updateOrderPaid(out_trade_no, Integer.valueOf(total_amount));
                notifyShop(out_trade_no, merchantReturnUrl);
            }
            log.info("************* 支付成功(支付宝异步通知) - 时间: {} *************", DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 交易状态: {}", trade_status);
            log.info("*****************************************************************************");
            return "success";
        } else {
            //验证失败
            log.info("验签失败, 时间: {}", DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN));
            return "fail";
        }
    }

    /**
     * 通知电商平台.
     */
    private void notifyShop(String merchantOrderId, String merchantReturnUrl) {
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("merchantOrderId", merchantOrderId);
        String httpStatus = restTemplate.postForObject(merchantReturnUrl, requestEntity, String.class);
        System.out.println("*** 通知电商后返回的状态码 httpStatus: " + httpStatus + " ***");
        log.info("*** 通知电商后返回的状态码 httpStatus: {} ***", httpStatus);
    }


    /**
     * 测试.
     *
     * @return -
     */
    @GetMapping("test")
    @Operation(summary = "测试")
    public BaseResponse test() {
        paymentOrderService.updateOrderPaid("190718FW17BFP8SW", 1001);
        return BaseResponse.ok();
    }

}
